<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Article extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'index_admin/login' );
			exit ();
		}
	}
	/*
	 * 返回文章列表
	 */
	public function index() {
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page=10;//暂定为10条
		
		$config['base_url']=site_url('article/index');
		$this->load->model ( 'article_model' );
	
		// 数据总数
		$config ['total_rows'] = $this->article_model->count_articles();
		//$config ['total_rows']=200; 
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config['uri_segment'] =3;
		
		$this->pagination->initialize($config);
		$data['links']=$this->pagination->create_links();
		//偏移量
		$offset=intval($this->uri->segment(3));
		$data ['articles'] = $this->article_model->find_articles ($per_page,$offset);
		$data ['title'] = '文章列表 - 文章管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'article/index' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回添加文章页面
	 */
	public function add() {
		$this->load->model ( 'category_model' );
		$data ['categories'] = $this->category_model->find_all_categories ();
		$data ['title'] = '添加文章 - 文章管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'article/add' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回编辑文章页面
	 */
	public function edit() {
		$id = $this->uri->segment(4);
		$this->load->model ( 'category_model' );
		$data ['categories'] = $this->category_model->find_all_categories ();
		$this->load->model ( 'article_model' );
		$data ['article']= $this->article_model->load ( $id );
		$data ['title'] = '编辑文章 - 文章管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'article/edit' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 保存或者更新文章的信息
	 */
	public function save() {
		$id = $this->input->post('id');
		$article = array (
				'title' => $this->input->post ( 'title' ),
				'class' => $this->input->post ( 'category' ),
				'content' => $this->input->post ( 'editor' ),
				'date' => date ( "Y-m-d H:i:s" )
		);
		$this->load->model ( 'article_model' );
		if ($id) {
			if($this->article_model->update ( $id, $article )){
				return_json(TRUE,'','修改成功！'); 
			}else{
				return_json(FALSE,'','信息未改动！');
			}
		} else {
			$articleid=$this->article_model->create ( $article );
			if(!empty($articleid)){
				return_json(TRUE,'','添加成功！'); 
			}else{
				return_json(FALSE,'','添加失败！');
			}
		}
	}
	/*
	 * 删除文章信息
	 */
	public function delete() {
		$id = $this->input->post('id');
		$this->load->model ( 'article_model' );
		if ($this->article_model->delete ( $id )) {
			return_json(TRUE,'','删除成功！'); 
		}else{
			return_json(TRUE,'','删除失败！');
		}
	}
}